package com.whfc.ms.api.fvs.controller;

import com.whfc.common.base.BaseController;
import com.whfc.common.constant.NameConst;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.*;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.SessionAttr;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fvs.dto.*;
import com.whfc.fvs.enums.FvsDevicePtzOption;
import com.whfc.fvs.param.FvsDeviceAddParam;
import com.whfc.fvs.param.FvsDeviceEditParam;
import com.whfc.fvs.param.FvsDeviceListParam;
import com.whfc.ms.api.fvs.service.MsFvsDeviceService;
import com.whfc.ms.api.fvs.service.MsFvsGroupService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;

/**
 * 视频监控
 *
 * @author guodong_sun
 * @Description:
 * @date 2019年10月24日
 */
@RestController
@RequestMapping("/ms/api/fvs")
@Validated
public class FvsDeviceController extends BaseController {

    @Autowired
    private MsFvsDeviceService msFvsDeviceService;

    @Autowired
    private MsFvsGroupService fvsGroupService;
    /**
     * 获取视频设备列表
     *
     * @param user     user
     * @param pageNum  pageNum
     * @param pageSize pageSize
     * @param keyword  keyword
     * @return Result
     */
    @GetMapping("/device/list")
    public Result deviceList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @RequestParam("pageNum") Integer pageNum,
                             @RequestParam("pageSize") Integer pageSize,
                             @RequestParam(value = "keyword", required = false) String keyword,
                             @RequestParam(value = "deviceType", required = false) Integer deviceType,
                             @RequestParam(value = "deviceStatus", required = false) Integer deviceStatus,
                             @RequestParam(value = "webcamType", required = false) Integer webcamType,
                             @RequestParam(value = "platform", required = false) String platform,
                             @RequestParam("deptId") Integer deptId,
                             @RequestParam(value = "groupId", required = false) Integer groupId) {
        logger.info("获取设备监控列表：loginer:{},pageNum:{},pageSize:{},keyword:{},deviceType:{},deviceStatus:{},webcamType:{},platform:{},deptId:{},groupId:{},",
                user.getUsername(), pageNum, pageSize, keyword, deviceType, deviceStatus, webcamType, platform, deptId, groupId);
        FvsDeviceListParam param = new FvsDeviceListParam();
        param.setDeviceType(deviceType);
        param.setDeptId(deptId);
        param.setGroupId(groupId);
        param.setPageNum(pageNum);
        param.setPageSize(pageSize);
        param.setKeyword(keyword);
        param.setDeptId(deptId);
        param.setDeviceStatus(deviceStatus);
        param.setDeviceType(deviceType);
        param.setWebcamType(webcamType);
        param.setPlatform(platform);
        PageData<FvsDeviceDTO> pageData = msFvsDeviceService.deviceList(param);
        return ResultUtil.success(pageData);
    }

    /**
     * 获取监控设备详情
     *
     * @param user user
     * @param id   id
     * @return Result
     */
    @GetMapping("/device/detail")
    public Result deviceDetail(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                               @RequestParam("id") Integer id) {
        logger.info("获取监控设备详情：loginer:{},id:{}", user.getUsername(), id);
        FvsDeviceDTO detail = msFvsDeviceService.detail(id);
        return ResultUtil.success(detail);
    }

    /**
     * 添加监控设备
     *
     * @param user    user
     * @param request request
     * @return Result
     */
    @RequiresPermissions("fvs/mach/add")
    @PostMapping("/device/add")
    public Result addDevice(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                            @Validated @RequestBody FvsDeviceAddParam request) {
        logger.info("添加监控设备：loginer:{},FvsDeviceAddParam:{}", user.getUsername(), request.toString());
        msFvsDeviceService.deviceAdd(request);
        return ResultUtil.success();
    }


    /**
     * 编辑监控设备
     *
     * @param user    user
     * @param request request
     * @return Result
     */
    @RequiresPermissions("fvs/mach/edit")
    @PostMapping("/device/edit")
    public Result editDevice(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @Validated @RequestBody FvsDeviceEditParam request) {
        logger.info("编辑监控设备：loginer:{},FvsDeviceEditParam:{}", user.getUsername(), request.toString());
        msFvsDeviceService.deviceEdit(request);
        return ResultUtil.success();
    }

    @PostMapping("/device/editSort")
    public Result editSort(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @Validated @RequestBody FvsDeviceEditParam request) {
        logger.info("编辑监控设备：loginer:{},FvsDeviceEditParam:{}", user.getUsername(), request.toString());
        msFvsDeviceService.deviceEdit(request);
        return ResultUtil.success();
    }
    /**
     * 删除监控设备
     *
     * @param user user
     * @param id   id
     * @return Result
     */
    @RequiresPermissions("fvs/mach/del")
    @PostMapping(value = "/device/del/{id}")
    public Result delDevice(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                            @PathVariable("id") Integer id) {
        logger.info("删除监控设备：loginer:{},id:{}", user.getUsername(), id);
        msFvsDeviceService.delDevice(id);
        return ResultUtil.success();
    }

    /**
     * 获取视频监控列表
     *
     * @param user     user
     * @param pageNum  pageNum
     * @param pageSize pageSize
     * @param deptId   deptId
     * @param keyword  keyword
     * @return Result
     */
    @GetMapping(value = "/list", params = {"pageNum", "pageSize"})
    public Result list(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                       @RequestParam("pageNum") Integer pageNum,
                       @RequestParam("pageSize") Integer pageSize,
                       @RequestParam(value = "deptId") Integer deptId,
                       @RequestParam(value = "webcamType", required = false) Integer webcamType,
                       @RequestParam(value = "deviceStatus", required = false) Integer deviceStatus,
                       @RequestParam(value = "keyword", required = false) String keyword,
                       @RequestParam(value = "groupId", required = false) Integer groupId) {
        logger.info("获取视频监控列表(分页)：loginer:{},pageNum:{},pageSize:{},deptId:{},keyword:{},webcamType:{},deviceStatus:{},groupId:{}",
                user.getUsername(), pageNum, pageSize, deptId, webcamType, deviceStatus, keyword, groupId);
        FvsDeviceListParam param = new FvsDeviceListParam();
        param.setDeptId(deptId);
        param.setPageNum(pageNum);
        param.setPageSize(pageSize);
        param.setKeyword(keyword);
        param.setGroupId(groupId);
        param.setDeviceStatus(deviceStatus);
        param.setWebcamType(webcamType);
        PageData<FvsDeviceDTO> pageData = msFvsDeviceService.list(param);
        return ResultUtil.success(pageData);
    }

    @GetMapping("/list")
    public Result list(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                       @RequestParam(value = "deptId") Integer deptId,
                       @RequestParam(value = "webcamType", required = false) Integer webcamType,
                       @RequestParam(value = "deviceStatus", required = false) Integer deviceStatus,
                       @RequestParam(value = "keyword", required = false) String keyword,
                       @RequestParam(value = "groupId", required = false) Integer groupId) {
        logger.info("获取视频监控列表(不分页)：loginer:{},deptId:{},keyword:{},webcamType:{},deviceStatus:{},groupId:{}",
                user.getUsername(), deptId, webcamType, deviceStatus, keyword, groupId);
        FvsDeviceListParam param = new FvsDeviceListParam();
        param.setDeptId(deptId);
        param.setKeyword(keyword);
        param.setGroupId(groupId);
        param.setDeviceStatus(deviceStatus);
        param.setWebcamType(webcamType);
        ListData<FvsDeviceDTO> listData = msFvsDeviceService.listData(param);
        return ResultUtil.success(listData);
    }


    /**
     * 获取视频监控详情
     *
     * @param user user
     * @param id   id
     * @return Result
     */
    @GetMapping("/detail")
    public Result detail(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                         @RequestParam("id") Integer id) {
        logger.info("获取视频监控详情：loginer:{},id:{}", user.getUsername(), id);
        FvsDeviceDTO appFvsDTO = msFvsDeviceService.detail(id);
        return ResultUtil.success(appFvsDTO);
    }


    /**
     * 获取视频监控直播地址
     *
     * @param user user
     * @param id   id
     * @return Result
     */
    @GetMapping(value = "/stream/url")
    public Result getStreamUrl(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                               @RequestParam("id") Integer id) {
        logger.info("获取视频监控直播地址：loginer:{},id:{}", user.getUsername(), id);
        FvsStreamDTO streamUrl = msFvsDeviceService.getStreamUrl(id);
        return ResultUtil.success(streamUrl);
    }

    /**
     * 获取视频监控直播地址
     *
     * @param id id
     * @return Result
     */
    @GetMapping(value = "/anon/stream/url")
    public Result anonGetStreamUrl(@RequestParam("id") Integer id) {
        logger.info("匿名获取视频监控直播地址：id:{}", id);
        FvsStreamDTO streamUrl = msFvsDeviceService.getStreamUrl(id);
        return ResultUtil.success(streamUrl);
    }


    /**
     * 获取视频监控录像地址
     *
     * @param user user
     * @param id   id
     * @param date date
     * @return Result
     */
    @GetMapping(value = "/record/list")
    public Result getRecordList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                                @RequestParam("id") Integer id,
                                @RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        logger.info("获取视频监控录像地址：loginer:{},id:{},date:{}", user.getUsername(), id, date);
        Date startTime = DateUtil.getDateBegin(date);
        Date endTime = DateUtil.getDateEnd(date);
        ListData<FvsRecordDTO> recordList = msFvsDeviceService.getRecordList(id, startTime, endTime);
        return ResultUtil.success(recordList);
    }

    /**
     * 获取视频监控token
     *
     * @param user   user
     * @param deptId id
     * @return Result
     */
    @GetMapping(value = "/token")
    public Result token(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                        @RequestParam("deptId") Integer deptId,
                        @RequestParam("platform") Integer platform) {
        logger.info("获取视频监控token：loginer:{},deptId:{},platform:{}", user.getUsername(), deptId, platform);
        FvsTokenDTO tokenDTO = msFvsDeviceService.getToken(deptId, platform);
        return ResultUtil.success(tokenDTO);
    }


    /**
     * 获取视频监控token
     *
     * @param deptId id
     * @return Result
     */
    @GetMapping(value = "/anon/token")
    public Result anonToken(@RequestParam("deptId") Integer deptId,
                            @RequestParam("platform") Integer platform) {
        logger.info("匿名获取视频监控token：deptId:{},platform:{}", deptId, platform);
        FvsTokenDTO tokenDTO = msFvsDeviceService.getToken(deptId, platform);
        return ResultUtil.success(tokenDTO);
    }

    @GetMapping(value = "/log")
    public Result log(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                      @RequestParam("deptId") Integer deptId,
                      @RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        logger.info("视频日志：loginer:{},deptId:{},date:{}", user.getUsername(), deptId, date);
        FvsLogDTO data = msFvsDeviceService.log(deptId, date);
        return ResultUtil.success(data);
    }

    @PostMapping("/ptz")
    public Result ptz(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                      @RequestParam("deviceId") Integer deviceId,
                      @RequestParam("ptzOption") Integer ptzOption) {
        logger.info("视频监控云台操作：loginer:{},deviceId:{}，ptzOption:{}",
                user.getUsername(), deviceId, ptzOption);
        FvsDevicePtzOption devicePtzOption = FvsDevicePtzOption.parseValue(ptzOption);
        if (devicePtzOption == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "操作类型错误.");
        }
        msFvsDeviceService.ptz(deviceId, devicePtzOption);
        return ResultUtil.success();
    }


    @PostMapping("/anon/ptz")
    public Result anonPtz(@RequestParam("deviceId") Integer deviceId,
                          @RequestParam("ptzOption") Integer ptzOption) {
        logger.info("匿名视频监控云台操作：deviceId:{}，ptzOption:{}", deviceId, ptzOption);
        FvsDevicePtzOption devicePtzOption = FvsDevicePtzOption.parseValue(ptzOption);
        if (devicePtzOption == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "操作类型错误.");
        }
        msFvsDeviceService.ptz(deviceId, devicePtzOption);
        return ResultUtil.success();
    }


    /**
     * 获取磅房视频监控列表
     *
     * @param user     user
     * @param pageNum  pageNum
     * @param pageSize pageSize
     * @param deptId   deptId
     * @param keyword  keyword
     * @return Result
     */
    @GetMapping(value = "/list/pound", params = {"pageNum", "pageSize"})
    public Result listPround(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                       @RequestParam("pageNum") Integer pageNum,
                       @RequestParam("pageSize") Integer pageSize,
                       @RequestParam(value = "deptId") Integer deptId,
                       @RequestParam(value = "webcamType", required = false) Integer webcamType,
                       @RequestParam(value = "deviceStatus", required = false) Integer deviceStatus,
                       @RequestParam(value = "keyword", required = false) String keyword
                       ) {
        logger.info("获取视频监控列表(分页)：loginer:{},pageNum:{},pageSize:{},deptId:{},keyword:{},webcamType:{},deviceStatus:{},groupId:{}",
                user.getUsername(), pageNum, pageSize, deptId, webcamType, deviceStatus, keyword);
        ListData<FvsGroupDTO> listData = fvsGroupService.list(deptId);
        Integer groupId = null;
        FvsDeviceListParam param = new FvsDeviceListParam();
        for (FvsGroupDTO data: listData.getList()) {
            Integer editFlag = data.getEditFlag();
            String groupName = data.getGroupName();
            if(editFlag == 0&& NameConst.DEFAULT_POUND_NAME.equals(groupName)){
                groupId = data.getGroupId();
                break;
            }
        }
        if (null == groupId){
            return ResultUtil.success(new PageData(new ArrayList(),pageNum,pageSize,1,0L));
        }
        param.setDeptId(deptId);
        param.setPageNum(pageNum);
        param.setPageSize(pageSize);
        param.setKeyword(keyword);
        param.setGroupId(groupId);
        param.setDeviceStatus(deviceStatus);
        param.setWebcamType(webcamType);
        PageData<FvsDeviceDTO> pageData = msFvsDeviceService.list(param);
        return ResultUtil.success(pageData);
    }

}
